import { UtilProvider } from './../../providers/common/util';
import { AuthProvider } from './../../providers/common/auth';
import { HttpProvider } from './../../providers/common/http';
// import { Http } from '@angular/http';
import { HTTP } from '@ionic-native/http';
import { FormBuilder, Validators } from '@angular/forms';
import { NavController, NavParams } from 'ionic-angular';
import { Component } from '@angular/core';
import { TabsPage } from '../tabs/tabs';
import { HttpClient } from '@angular/common/http';
import { ip } from '../../providers/ip/ip';
import { RegisterPage } from '../register/register';

/**
 * Generated class for the LoginPage page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */

@Component({
	selector: 'page-login',
	templateUrl: 'login.html'
})
export class LoginPage {
	path: string = 'http://192.168.43.108/api/login';
	backgrounds = [
		'assets/imgs/background/background-1.jpg',
		'assets/imgs/background/background-2.jpg',
		'assets/imgs/background/background-3.jpg',
		'assets/imgs/background/background-4.jpg'
	];
	loginForm: any;
	data:any;
	submitted = false;
	constructor(
		public formBuilder: FormBuilder,
		private navCtrl: NavController,
		private utilProvider: UtilProvider,
		private http: HttpClient
	) {
		this.loginForm = formBuilder.group({
			email: [ '', Validators.required ],
			password: [ '', Validators.compose([ Validators.minLength(6), Validators.required ]) ]
		});
	}

	ionViewDidLoad() {
		console.log('Hello LoginBackgroundSlider Page');
	}

	openResetPassword() {
		console.log('Reset password clicked');
	}
	toregister() {
		this.navCtrl.push(RegisterPage);
	}
	doLogin() {
		this.submitted = true;
		if (!this.loginForm.valid) {
			this.utilProvider.error('Invalid or empty data');
			console.log('Invalid or empty data');
		} else {
			let that = this;
			const userEmail = this.loginForm.value.email;
			const userPassword = this.loginForm.value.password;
			// that.navCtrl.push(TabsPage);
			alert(userEmail);
			alert(userPassword);
			alert(ip + 'api/login');
			this.http.post(ip + 'api/login', { phone: userEmail, password: userPassword }, {}).subscribe(
				function(data) {
					console.log(data);
					// alert(data.data.token);
					that.data=data;
					localStorage.setItem('token', that.data.data.token);
					console.log(localStorage.getItem('token'));
					let ws = new WebSocket("ws://192.168.43.108:7272");
					if(that.data.errcode!=-1)
					that.navCtrl.push(TabsPage);
					else
					alert("账号密码错误");
				},
				function(err) {
					console.log(err);
				}
			);
			console.log('user data', userEmail, userPassword);
			// this.authProvider.login('gz001', '123456').then((resp) => {
			// 	// this.navCtrl.push(TabsPage);
			// });
		}
	}
}
